<template>
  <!-- 弹框内容 -->
  <el-dialog title="问题工单" :visible.sync="showComplaintEdit" width="50%">
    <div>
      <el-form ref="problemTicketEdit" :model="problemTicketEdit" :rules="problemTicketEditrules" label-width="100px">
        <el-form-item label="后台单号">
          <span v-if="problemTicketEdit.xmbzNo">{{ problemTicketEdit.xmbzNo }}</span>
          <span v-else>-</span>
        </el-form-item>
        <el-form-item label="创建工单时间">
          <span>{{ problemTicketEdit.createTime }}</span>
        </el-form-item>
        <el-form-item label="平台单号">
          <span v-if="problemTicketEdit.platformNo">{{ problemTicketEdit.platformNo }}</span>
          <span v-else>-</span>
        </el-form-item>
        <el-form-item label="部门失误类型">
          <div v-if="proStatus == 'update'">
            <ele-multi-cascader clearable v-model="problemEditor" :options="errorTypeList" :inputValue="configTips"
              separator=">" placeholder="请选择部门失误类型" style="width: 280px;"></ele-multi-cascader>
          </div>
          <span v-if="proStatus == 'view'">{{ problemTicketEdit.responsibleDepartmentErrorText }}</span>
        </el-form-item>
        <el-form-item label="投诉等级">
          <ComplaintLevelSelect v-model="problemTicketEdit.complaintLevel" placeholder="请选择投诉等级" v-if="proStatus == 'update'"
            size="small">
          </ComplaintLevelSelect>
          <span v-if="proStatus == 'view'">{{ problemTicketEdit.complaintLevelName }}</span>
        </el-form-item>
        <el-form-item label="处理状态">
          <span >{{ problemTicketEdit.handleStateName }}</span>
        </el-form-item>
        <el-form-item label="投诉渠道">
          <ComplaintChannelSelect v-model="problemTicketEdit.complaintChannelName" placeholder="请选择投诉等级" v-if="proStatus == 'update'"
            size="small"></ComplaintChannelSelect>
          <span v-if="proStatus == 'view'">{{ problemTicketEdit.complaintChannelName }}</span>
        </el-form-item>
        <el-form-item label="责任人">
          <el-input v-model.trim="problemTicketEdit.personLiable" v-if="proStatus == 'update'" size="small"
            type="textarea" maxlength="10" show-word-limit></el-input>
          <span v-if="proStatus == 'view'">{{ problemTicketEdit.personLiable }}</span>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model.trim="problemTicketEdit.phone" v-if="proStatus == 'update'" class="inputType" size="small"
            onkeyup="value=value.replace(/[^\-?\d.]/g,'').slice(0,11)"
            onafterpaste="value=value.replace(/[^\-?\d.]/g,'').slice(0,11)"></el-input>
          <span v-if="proStatus == 'view'">{{ problemTicketEdit.phone }}</span>
        </el-form-item>
        <el-form-item label="投诉内容" required>
          <el-input type="textarea" v-model.trim="problemTicketEdit.complaintContent" v-if="proStatus == 'update'"
            maxlength="500" show-word-limit :autosize="{ minRows: 4, maxRows: 6 }"></el-input>
          <span v-if="proStatus == 'view'" class="processingResults">{{ problemTicketEdit.complaintContent }}</span>
        </el-form-item>
        <el-form-item label="处理结果" required>
          <el-input type="textarea" v-model.trim="problemTicketEdit.processingResults" v-if="proStatus == 'update'"
            maxlength="250" show-word-limit :autosize="{ minRows: 4 }"></el-input>
          <span v-else class="processingResults">{{ problemTicketEdit.processingResults }}</span>
        </el-form-item>

        <!-- 问题工单 -->
        <el-form-item label="图片附件:" prop="title">
          <div style="margin-bottom: 15px;">
            <el-upload action="/api/xmbz-goods/file/upload" :data="{ tag: 'problem' }" :on-exceed="handleExceed"
              list-type="picture-card" :on-success="handProblemSuccess" :limit="10" :file-list="singproblemForm.pics"
              :on-remove="beforeProblemRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>

        <div class="ta-c">
          <el-button type="primary" plain @click="handlerEditproblem()" size="small"
            v-if="problemTicketShows">编辑</el-button>
          <el-button type="info" size="small" plain @click="handlerLogproblem(problemTicketEdit)"
            v-show="problemTicketOther">日志</el-button>
        </div>
        <!-- 修改状态 -->
        <div v-show="!problemTicketOther" class='ta-c'>
          <el-button class="mr-100" type="success" size="small" plain v-if="problemTicketShowEdits" @click="handlerSaveproblem(0)">保存</el-button>
          
          <el-button v-for="item in dealstatusList" :key="item.dictKey" :type="getBtnType(item)" size="small" plain @click="handlerSaveproblem(item.dictKey)" class="ml=10">{{item.dictValue}}</el-button>
        </div>
      </el-form>
    </div>

    <orderLogDialog ref="orderLogDialog"></orderLogDialog>
  </el-dialog>
</template>

<script>
import {
  updateWorkOrderProblem, // 问题
} from "@/api/workorder"
import orderLogDialog from '@/components/dialog/orderLogDialog'
export default {
  props: {
    dealstatusList: {
      type: Array,
      default: () => []
    },
    errorTypeList: {
      type: Array,
      default: () => []
    },
  },
  data() {
    return {
      showComplaintEdit: false,
      proStatus: 'view',
      problemEditor: [],       // 问题编辑数组
      problemTicketEdit: {},
      problemTicketShows: true,
      problemTicketShowEdits: false,
      problemTicketOther: true,
      singproblemForm: {     // 问题图片数组
        pics: []
      },
      problemTicketEditrules: {
        personLiable: [
          {
            max: 10,
            message: "长度在10个字符以内",
            trigger: "blur"
          }
        ],
        complaintContent: [
          {
            required: true,
            message: "投诉内容必填",
            trigger: "blur"
          }
        ],
        processingResults: [
          {
            required: true,
            message: "处理结果必填",
            trigger: "blur"
          }
        ]
      },
      configTips: null,
    };
  },
  methods: {
    show(row, status) {
      this.problemEditor = row.responsibleDepartmentError.split(',')
      console.log(row.responsibleDepartmentError.split(','), '问题工单')
      let arr = []
      if (row.extJson) {
        JSON.parse(row.extJson).img.map(item => {
          let obj = {}
          obj['url'] = item
          arr.push(obj)
        })
        this.singproblemForm.pics = arr
      } else {
        this.singproblemForm.pics = []
      }
      //问题工单详情进入
      this.problemTicketEdit = row
      this.proStatus = status

      if (status == 'view') {
        this.problemTicketShowEdits = false
        this.problemTicketOther = true
        this.problemTicketShows = true
      } else if (status == 'update') {
        this.problemTicketShowEdits = true
        this.problemTicketOther = false
        this.problemTicketShows = false
      }

      if (this.$refs['problemTicketEdit'] !== undefined) {
        this.$refs['problemTicketEdit'].resetFields()
      }
      this.showComplaintEdit = true
    },
    handlerEditproblem() {
      //问题工单编写
      this.showComplaintEdit = true
      this.proStatus = "update"
      this.problemTicketShows = false
      this.problemTicketShowEdits = true
      this.problemTicketOther = false
    },
    //  问题工单 上传成功
    handProblemSuccess(response) {
      this.singproblemForm.pics.push({
        url: response.data
      })
    },
    //  问题工单 删除
    beforeProblemRemove(index) {
      this.singproblemForm.pics.map((item, ids) => {
        if (item.uid == index.uid) {
          this.singproblemForm.pics.splice(ids, 1)
        }
      })
      //  this.singproblemForm.pics.splice(index, 1);
    },
    //  共用选择多图片
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 10 个文件，本次选择了 ${files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    handlerLogproblem(item) {
      //问题工单日志
      this.$refs.orderLogDialog.show({orderId: item.orderId})
    },
    handlerSaveproblem(submitType) {
      this.$refs['problemTicketEdit'].validate(valid => {
        if (valid) {
          const errorMsg = this.validateParams()
          if (errorMsg) {
            this.$message({
              type: "warning",
              message: errorMsg
            })
            return false
          } else {
            const Saveproblem = this.getParams(submitType)
            //问题工单保存
            this.$confirm("确定修改问题工单信息了吗, 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
              .then(() => {
                updateWorkOrderProblem(Saveproblem).then(() => {
                  this.showComplaintEdit = false
                  this.$message({
                    type: "success",
                    message: "保存成功"
                  })
                  this.problemTicketShows = true
                  this.problemTicketShowEdits = false
                  this.$emit('updated')
                })
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消修改"
                })
              })
          }
        }
      })
    },
    getParams(submitType) {
      const item = this.problemTicketEdit
      const params = {
        id: item.id,
        responsibleDepartmentError: this.problemEditor.join(',') || null,   // 问题部门失误类型
        orderId: item.orderId,
        responsibleDepartment: '', //		责任部门 
        departmentErrorType: '', //		部门失误类型
        complaintLevel: item.complaintLevel, //			投诉等级
        handleState: submitType == 0 ? item.handleState : submitType, //	投诉状态
        complaintChannel: item.complaintChannel, //			投诉渠道
        personLiable: item.personLiable, //			责任人
        platformNo: item.platformNo, //		第三方平台单号
        phone: item.phone, //		手机号
        complaintContent: item.complaintContent, //				投诉内容
        processingResults: item.processingResults, //	  处理结果
        extJson: JSON.stringify({ 'img': this.singproblemForm.pics.map(item => item.url) }),  // 问题图片列表
        submitType: submitType,
      }
      return params
    },
    validateParams() {
      if (!this.problemEditor.length) {
        return '部门失误类型不能为空'
      } else if (!this.problemTicketEdit.complaintContent) {
        return '投诉内容不能为空'
      } else if (!this.problemTicketEdit.processingResults) {
        return '处理结果不能为空'
      }
    },
    getBtnType(item) {
      const typeMap = {
        1: 'primary',
        2: 'success',
        3: 'danger',
      }
      return typeMap[item.dictKey] || ''
    }
  },
  components: {
    orderLogDialog
  }
};
</script>
<style lang="scss" scoped>
</style>